package com.zhuzhe.blog.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.zhuzhe.blog.base.JsonData;
import com.zhuzhe.blog.base.ResponseData;
import com.zhuzhe.blog.convert.Convert;
import com.zhuzhe.blog.system.entity.SysMenu;
import com.zhuzhe.blog.system.entity.SysRoleMenu;
import com.zhuzhe.blog.system.requestDto.SysMenuDto;
import com.zhuzhe.blog.system.responseVo.SysMenuListVo;
import com.zhuzhe.blog.system.mapper.SysMenuMapper;
import com.zhuzhe.blog.system.mapper.SysRoleMenuMapper;
import com.zhuzhe.blog.system.service.ISysMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 菜单信息表 服务实现类
 * </p>
 *
 * @author u53
 * @since 2020-10-13
 */
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements ISysMenuService {


    @Autowired
    private SysRoleMenuMapper sysRoleMenuMapper;


    /**
     * 查询所有菜单
     * @author   whh
     * @param sysMenuDto
     * @return      com.zhuzhe.blog.base.ResponseData<com.zhuzhe.blog.system.entity.SysMenu>
     * @exception
     * @date        2020/10/14 21:15
     */
    @Override
    public ResponseData<SysMenuListVo> queryList(SysMenuDto sysMenuDto) {
        //todo 条件查询所有菜单
        QueryWrapper<SysMenu> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(sysMenuDto.getName())) {
            queryWrapper.like("name", sysMenuDto.getName());
        }
        queryWrapper.orderByDesc("sort").orderByDesc("update_date");
        //转换VO
        List<SysMenuListVo> sysMenus = Convert.convertList( baseMapper.selectList(queryWrapper),SysMenuListVo.class) ;

        //将菜单封装成树形菜单并响应
        List<SysMenuListVo> sysMenuList = this.buildTree(sysMenus);
        return JsonData.success(sysMenuList);
    }

    /**
     * 生成树形菜单
     * @author   whh
     * @param sysMenus
     * @return      java.util.List<com.zhuzhe.blog.system.entity.SysMenu>
     * @exception
     * @date        2020/10/14 20:49
     */
    private List<SysMenuListVo> buildTree(List<SysMenuListVo> sysMenus) {
        //获取根菜单
        List<SysMenuListVo> rootMenuList = new ArrayList<>();
        for (SysMenuListVo sysMenu : sysMenus) {
            if (sysMenu.getParentId().equals("0")) {
                rootMenuList.add(sysMenu);
            }
        }
        //获取根菜单下子菜单
        for (SysMenuListVo rootSysMenu : rootMenuList) {
            rootSysMenu.setChildren(this.childrenMenu(sysMenus, rootSysMenu));
        }
        return rootMenuList;
    }

    /**
     * 根据父级菜单筛选子菜单
     * @author   whh
     * @param sysMenus
 * @param rootSysMenu
     * @return      java.util.List<com.zhuzhe.blog.system.entity.SysMenu>
     * @exception
     * @date        2020/10/14 20:49
     */
    private List<SysMenuListVo> childrenMenu(List<SysMenuListVo> sysMenus, SysMenuListVo rootSysMenu) {

        //循环所有菜单，筛选出rootSysMenu的所有子菜单
        List<SysMenuListVo> childrenMenuList = new ArrayList<>();
        for (SysMenuListVo childrenMenu : sysMenus){
            if (childrenMenu.getParentId().equals(rootSysMenu.getId())){
                //获取childrenMenu的子菜单
                childrenMenu.setChildren(childrenMenu(sysMenus,childrenMenu));
                childrenMenuList.add(childrenMenu);
            }
        }
        return childrenMenuList;
    }


    /**
     * 删除菜单及子菜单
     * @author   whh
     * @param id
     * @return      com.zhuzhe.blog.base.ResponseData<java.lang.Integer>
     * @exception
     * @date        2020/10/14 21:16
     */
    @Override
    @Transactional
    public ResponseData<Integer> deleteById(String id) {
        if(StringUtils.isEmpty(id)){
            return JsonData.fail("对不起,菜单id不能为空!");
        }
        QueryWrapper<SysRoleMenu> roleMenuQueryWrapper = new QueryWrapper<>();
        roleMenuQueryWrapper.eq("menu_id",id);
        Integer integer = sysRoleMenuMapper.selectCount(roleMenuQueryWrapper);
        if (integer > 0){
            return JsonData.fail("对不起,此菜单已被使用,不能删除!");
        }

        //todo 删除当前id菜单
        baseMapper.deleteById(id);
        List<SysMenu> sysMenuList = baseMapper.selectList(new QueryWrapper<>());
        // 需要删除的菜单集合
        List<String> menuIds = new ArrayList<>();
        menuIds.add(id);
        //递归筛选所有子级菜单id
        this.getDelMenuIds(sysMenuList,id,menuIds);
        LambdaQueryWrapper<SysMenu> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(SysMenu::getId,menuIds);
        //删除子菜单
        baseMapper.delete(queryWrapper);
        return JsonData.success(id);
    }


    /**
     * 根据菜单id查询菜单详情
     * @author   whh
     * @param id
     * @return      com.zhuzhe.blog.base.ResponseData<com.zhuzhe.blog.system.entity.SysMenu>
     * @exception
     * @date        2020/10/14 23:55
     */
    @Override
    public ResponseData<SysMenu> viewMenu(String id) {
        if(StringUtils.isEmpty(id)){
            return JsonData.fail("对不起,菜单id不能为空!");
        }
        SysMenu sysMenu = baseMapper.selectById(id);
        if (null == sysMenu){
            return  JsonData.fail("对不起,菜单不存在");
        }
        return JsonData.success(sysMenu);
    }

    /**
     * 修改菜单
     * @author   whh
     * @param sysMenuDto
     * @return      com.zhuzhe.blog.base.ResponseData<java.lang.Integer>
     * @exception
     * @date        2020/10/14 23:55
     */
    @Override
    public ResponseData<Integer> updateMenu(SysMenuDto sysMenuDto) {

        if (StringUtils.isEmpty(sysMenuDto.getId())){
            return  JsonData.fail("id不能为空");
        }
        SysMenu sysMenu = new SysMenu();
        Convert.convertType(sysMenuDto,sysMenu);
        sysMenu.setUpdateDate(new Date());
        Integer updateById = baseMapper.updateById(sysMenu);
        return JsonData.success(updateById);
    }

    /**
     * 根据父级菜单id，筛选所有需要删除得菜单id
     * @author   whh
     * @param sysMenuList
     * @param id
     * @param menuIds
     * @return      void
     * @exception
     * @date        2020/10/14 22:20
     */
    private void getDelMenuIds(List<SysMenu> sysMenuList, String id, List<String> menuIds) {

        //筛选菜单
        for (SysMenu sysMenu : sysMenuList){
            if (sysMenu.getParentId().equals(id)){
                //筛选出子菜单的子菜单
                getDelMenuIds(sysMenuList,sysMenu.getId(),menuIds);
                menuIds.add(sysMenu.getId());
            }

        }
    }

    @Override
    public List<SysMenu> findByUserId(String userId) {
        // 通过用户id查询权限信息
        List<SysMenu> menuList = baseMapper.findByUserId(userId);
        if( CollectionUtils.isEmpty(menuList)
                || menuList.get(0) == null ) {
            return null;
        }
        return menuList;
    }
}
